import json
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.models import User
from django.views.decorators.csrf import csrf_exempt
from django.http import JsonResponse


@csrf_exempt
def register(request):
    """
    注册，适用于前后端分离，
    :param request:
    :return:  json数据
    """
    try:
        if request.method == 'GET':
            return
        body = request.body.decode()
        params = json.loads(body)  # dict
        username = params.get("username")
        email = params.get("email")
        password = params.get("password")
        password2 = params.get("password2")

        if not (username and email and password and password2):
            return JsonResponse({"status": -1, "message": "请输入完整参数"})
        if password != password2:
            return JsonResponse({"status": -1, "message": "两次输入密码不同"})

        params.pop("password2")
        if User.objects.filter(username=username).first():
            return JsonResponse({"status": -1, "message": "用户名已存在!"})
        User.objects.create_user(**params).save()
        return JsonResponse({"status": -1})
    except Exception as e:
        return JsonResponse({"status": -1, "message": "注册失败"})


def logins(request):
    """

    :param request:
    :return:
    """
    try:
        if request.method == "POST":
            body = request.body.decode()
            params = json.loads(body)  # dict
            username = params.get("username")
            pwd = params.get("password")
            if authenticate(username=username, password=pwd):
                login(request, username)
                return JsonResponse({'status': -1, 'username': username, 'is_super': request.user.is_superuser})
            else:
                return JsonResponse({"status": -1, "message": "用户名或密码错误"})
    except Exception as e:
        return JsonResponse({"status": -1, "error": "用户名或密码错误"})


def logouts(request):
    try:
        logout(request)
        return JsonResponse({'status': 0})
    except Exception as e:
        return JsonResponse({'status': -1})



